package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.model.product.SpuImage;
import com.atguigu.gmall.model.product.SpuInfo;
import com.atguigu.gmall.model.product.SpuSaleAttr;
import com.atguigu.gmall.model.product.SpuSaleAttrValue;
import com.atguigu.gmall.product.mapper.SpuImageMapper;
import com.atguigu.gmall.product.mapper.SpuSaleAttrMapper;
import com.atguigu.gmall.product.mapper.SpuSaleAttrValueMapper;
import com.atguigu.gmall.product.service.SpuImageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.product.service.SpuInfoService;
import com.atguigu.gmall.product.mapper.SpuInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
* @author lfy
* @description 针对表【spu_info(商品表)】的数据库操作Service实现
* @createDate 2022-03-05 09:33:47
*/
@Service
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoMapper, SpuInfo>
    implements SpuInfoService{

    @Autowired
    SpuInfoMapper spuInfoMapper;

    @Autowired
    SpuImageService spuImageService;

    @Autowired
    SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    SpuSaleAttrValueMapper spuSaleAttrValueMapper;


    /**
     * Spu大保存
     * @param spuInfo
     */
    @Transactional  //添加事务注解
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //1、spu_info信息保存
        spuInfoMapper.insert(spuInfo);

        Long id = spuInfo.getId();

        //2、spu_image都存一下
        List<SpuImage> list = spuInfo.getSpuImageList();
        if(list!=null && !list.isEmpty() ){
            for (SpuImage image : list) {
                image.setSpuId(id); //回填spu_id
            }
            spuImageService.saveBatch(list);
        }

        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        //3、spu_sale_attr 保存
        if(spuSaleAttrList!=null && !spuSaleAttrList.isEmpty()){
            for (SpuSaleAttr saleAttr : spuSaleAttrList) {
                saleAttr.setSpuId(id);//回填spu_id
                spuSaleAttrMapper.insert(saleAttr); //保存属性名
                //4、spu_sale_attr_value 保存
                List<SpuSaleAttrValue> valueList = saleAttr.getSpuSaleAttrValueList();
                for (SpuSaleAttrValue attrValue : valueList) {
                    attrValue.setSaleAttrName(saleAttr.getSaleAttrName()); //回填属性名
                    attrValue.setSpuId(id); //回填spuid
                    spuSaleAttrValueMapper.insert(attrValue);
                }
            }
        }


    }
}




